package com.util;

import org.apache.commons.collections.map.LRUMap;


public class SysCache {
	
	private static SysCache instance;
	private LRUMap cacheMap = null;
	
	
	private SysCache(){
		int maxCount = SysConfig.getInteger("cache.entity");
		if(maxCount <= 0){
			maxCount = 1000;
		}
		cacheMap = new LRUMap(maxCount);
	}

	public static synchronized SysCache getInstance() {
		if(instance == null){
			instance = new SysCache();
		}
		return instance;
	}
	
	private void put(SysCacheTypeEnum type, String key, Object value){
		cacheMap.put(type.name()+"_"+key, value);
	}
	
	public void put(BasePojo pojo){
		if(pojo != null && pojo.getId() != null){
			cacheMap.put(SysCacheTypeEnum.BASE_POJO.name()+"_"+pojo.getClass().getName()+"_"+pojo.getId(),pojo);
		}
	}
	
	private Object get(SysCacheTypeEnum type, String key){
		return cacheMap.get(type.name()+"_"+key);
	}
	
	public String getSysConfig(String key){
		key = key.toLowerCase();
		Object obj = this.get(SysCacheTypeEnum.SYS_CONFIG, key);
		if(obj != null){
			return obj.toString();
		}else{
			String ret = SysConfig.getItem(key);
			this.put(SysCacheTypeEnum.SYS_CONFIG, key, ret);
			return ret;
		}
	}
	
	public void remove(Class<BasePojo> classes, int id){
		cacheMap.remove(SysCacheTypeEnum.BASE_POJO.name()+"_"+classes.getName()+"_"+id);
	}
	
	public void reset(){
		instance = new SysCache();
	}
}

enum SysCacheTypeEnum{
	SYS_CONFIG,
	BASE_POJO;
}
